<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      width="80%"
      align-center
      :show-close="false"
      @open="handleOpen"
      @close="handleClose"
      destroy-on-close
      draggable
    >
      <template #header="{ close }">
        <div class="dialog-header flex justify-between items-center">
          <div>{{ title }}</div>
          <el-icon class="el-icon--left cursor-pointer" @click="close"
            ><CircleCloseFilled color="#fff"
          /></el-icon>
        </div>
      </template>
      <!-- 基本信息 -->
      <div class="bg-white mt-[10px]">
        <BaseHead>基本信息</BaseHead>
        <div class="p-[10px]">
          <el-form :model="editForm" :rules="rules" label-width="140px" ref="editFormRef">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="项目分类名称" prop="name">
                  <el-input v-model="editForm.name" placeholder="项目分类名称" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="编号"> {{ editForm.code }}</el-form-item>
              </el-col>
              <el-col :span="12" v-if="parentCategoryName">
                <el-form-item label="上级分类"> {{ parentCategoryName }}</el-form-item>
              </el-col>
              <!-- 横向项目分类设置时不显示以下几行 -->
              <template v-if="!isHxProject">
                <el-col :span="12">
                  <el-form-item label="教育部统计归属" prop="subjectClassId">
                    <el-radio-group v-model="editForm.subjectClassId" @change="subjectTypeChange">
                      <el-radio :value="item.code" v-for="item in subjectTypes" :key="item.id">{{
                        item.name
                      }}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="项目来源" prop="projectSourceId">
                    <el-select
                      v-model="editForm.projectSourceId"
                      placeholder="项目来源"
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="item in projectSourceTypes"
                        :key="item.id"
                        :label="item.label"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="项目级别" prop="projectLevelId">
                    <CommonRadio
                      paramsName="项目级别"
                      v-model="editForm.projectLevelId"
                      valueKey="code"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="支付来源" prop="paySourceId">
                    <CommonSelect
                      paramsName="支付来源"
                      placeholder="支付来源"
                      v-model="editForm.paySourceId"
                      valueKey="code"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="是否限制报告提交" prop="isProcessAlarm">
                    <el-radio-group v-model="editForm.isProcessAlarm">
                      <el-radio value="1">是</el-radio>
                      <el-radio value="0">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <!-- 选择否的话此行不显示 -->
                <template v-if="editForm.isProcessAlarm == 1">
                  <el-col :span="12">
                    <el-form-item label="中检报告限制在" prop="allowMiddleCheckDate">
                      <span>项目开始后</span>
                      <el-select
                        v-model="editForm.allowMiddleCheckDate"
                        style="width: 120px; margin: 0 5px"
                        clearable
                      >
                        <el-option v-for="item in 12" :key="item" :label="item" :value="item" />
                      </el-select>
                      <span>月</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="允许结项日期" prop="allowCompleteDate">
                      <span>项目计划结项前</span>
                      <el-select
                        v-model="editForm.allowCompleteDate"
                        style="width: 120px; margin: 0 5px"
                        clearable
                      >
                        <el-option v-for="item in 12" :key="item" :label="item" :value="item" />
                      </el-select>
                      <span>月</span>
                    </el-form-item>
                  </el-col>
                </template>
              </template>
              <el-col :span="24">
                <el-form-item label="备注" prop="note">
                  <el-input v-model="editForm.note" type="textarea" clearable />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <!-- 预算信息 -->
      <div class="bg-white mt-[10px]">
        <BaseHead style="border-bottom: 0">
          预算信息 <el-button @click="handeAdd">添加</el-button></BaseHead
        >
        <el-table :data="budgetStandardDateList" class="w-full" border>
          <el-table-column label="预算标准">
            <template #default="{ row }">
              <div class="flex items-center">
                <span class="no-empty-icon">*</span>
                <el-select v-model="row.budgetStandardId" clearable>
                  <el-option
                    v-for="item in standardList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="起始年度">
            <template #default="{ row }">
              <div class="flex items-center">
                <span class="no-empty-icon">*</span>
                <el-date-picker
                  v-model="row.startDate"
                  type="year"
                  claerable
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="结束年度">
            <template #default="{ row }">
              <div class="flex items-center">
                <span class="no-empty-icon">*</span>
                <el-date-picker
                  v-model="row.endDate"
                  type="year"
                  claerable
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="100" align="center">
            <template #default="{ $index }">
              <el-button type="primary" size="small" plain @click="handleDel($index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <div class="operate-btns">
            <el-button type="primary" @click="save">保存</el-button>
            <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import CommonSelect from "@/views/project/components/CommonSelect.vue";
import CommonRadio from "@/views/project/components/CommonRadio.vue";
import { addRecords, editRecords, getPrefix } from "@/api/project/zx/xmflsz";
import { getList } from "@/api/project/zx/ysbzsz";
import { getCommonData } from "@/api/project/common.js";
import { ElMessage } from "element-plus";
import { assignObj } from "@/utils/main";
const dialogVisible = ref(false);
const editFormRef = ref();
const projectClass = inject("projectClass");
//预算标准数据
const standardList = ref([]);
const parentCategoryName = ref(""); //添加子类时显示的上级分类名称
const budgetStandardDateList = ref([]);
const subjectTypes = ref([]);
const projectSourceTypes = ref([]);
const operateId = ref(null);
//预算标准一项
const budgetItem = {
  budgetStandardId: "",
  startDate: "",
  endDate: "",
};
const title = computed(() => {
  return operateId.value ? "分类编辑" : "分类新增";
});
//是否时横向项目
const isHxProject = computed(() => {
  return projectClass == "yfContract";
});
const editForm = reactive({
  name: "",
  code: "",
  subjectClassId: "", //教育部统计归属
  projectSourceId: "", //项目来源
  projectLevelId: "", //项目级别
  paySourceId: "", //支付来源
  isProcessAlarm: "0", //是否限制报告提交
  allowMiddleCheckDate: "", //中检报告限制在
  allowCompleteDate: "", //允许结项日期
  note: "",
  upCode: "",
  typeLevel: 1,
  parentId: "",
});
const rules = {
  name: [
    {
      required: true,
      message: "项目分类名称必填",
    },
    {
      pattern: /^[^-]*$/,
      message: "项目分类名称不能包含横杠！",
    },
  ],
  subjectClassId: [
    {
      required: true,
      message: "教育部统计归属必填",
    },
  ],
  projectSourceId: [
    {
      required: true,
      message: "项目来源必填",
    },
  ],
  paySourceId: [
    {
      required: true,
      message: "支付来源必填",
    },
  ],
  isProcessAlarm: [
    {
      required: true,
      message: "是否限制报告提交必填",
    },
  ],
};
// 新增
const add = (row) => {
  operateId.value = null;
  dialogVisible.value = true;
  //新增时 默认生成一行预算信息数据
  budgetStandardDateList.value.push(Object.assign({}, budgetItem));
  //row有值表示添加子类信息
  nextTick(() => {
    if (row) {
      parentCategoryName.value = row.belongType;
      editForm.upCode = row.code;
      editForm.typeLevel = row.typeLevel + 1;
      editForm.parentId = row.id;
    }
    //获取最大预算科目前缀
    getMaxPrefix();
  });
};
// 编辑
const edit = async (row) => {
  operateId.value = row.id;
  dialogVisible.value = true;
  nextTick(() => {
    assignObj(editForm, row);
    budgetStandardDateList.value = row.budgetStandardDateList;
  });
};
defineExpose({ add, edit });
//获取教育部统计归属数据
const getSubjectTypes = async () => {
  const params = {
    bizName: "教育部统计归属",
  };
  try {
    const res = await getCommonData(params);
    subjectTypes.value = res.data;
    if (editForm.subjectClassId == "") {
      editForm.subjectClassId = subjectTypes.value[0].code;
    }
    getProjectSource();
  } catch (error) {
    console.log(error);
  }
};
//获取项目来源数据
const getProjectSource = async () => {
  const params = {
    bizName: "项目来源",
    valueCascade: editForm.subjectClassId,
  };
  try {
    const res = await getCommonData(params);
    projectSourceTypes.value = res.data;
  } catch (error) {
    console.log(error);
  }
};
//教育部统计归属改变
const subjectTypeChange = () => {
  editForm.projectSourceId = "";
  getProjectSource();
};
//获取预算标准数据
const getStandardList = async () => {
  const params = {
    pageNum: 1,
    pageSize: 1000,
    projectClass,
  };
  try {
    const res = await getList(params);
    standardList.value = res.rows;
  } catch (error) {
    console.log(error);
  }
};
//获取最大预算科目前缀
const getMaxPrefix = async () => {
  try {
    const params = {
      projectClass,
      typeLevel: editForm.typeLevel,
      upCode: editForm.upCode,
    };
    const res = await getPrefix(params);
    const maxPrefix = res.data;
    //如果maxPrefix为空
    if (!maxPrefix) {
      //如果是第一级  默认生成编号01  此处需根据横向纵向校级判断前缀
      if (editForm.typeLevel == 1) {
        const charCode =
          projectClass == "zXProject" ? "Z" : projectClass == "yfContract" ? "H" : "X";
        editForm.code = charCode + "01";
      } else {
        //如果不是第一级 则是父级编号加01
        editForm.code = editForm.upCode + "01";
      }
    } else {
      //当前编号最后两位数字加1
      editForm.code = getCurrentPrefix(maxPrefix);
    }
  } catch (error) {
    console.log(error);
  }
};
//获取当前prefix的值
const getCurrentPrefix = (maxPrefix) => {
  const code = maxPrefix.slice(0, -2); //截取至最后两位数字 保留前面的编号
  const number = maxPrefix.slice(-2); //截取最后两位数字
  const num = parseInt(number) + 1; //去掉前导0 加1 生成新编号数值
  const newNumber = num.toString().padStart(2, "0"); //补全2位字符串
  return code + newNumber;
};
//点击添加预算信息
const handeAdd = () => {
  budgetStandardDateList.value.push(Object.assign({}, budgetItem));
};
//点击删除一行预算信息
const handleDel = (index) => {
  budgetStandardDateList.value.splice(index, 1);
};
const emit = defineEmits(["save-success"]);
//点击保存
const save = () => {
  try {
    editFormRef.value?.validate(async (valid) => {
      if (valid) {
        /**预算信息校验开始 */
        //校验是否添加有预算信息
        if (!budgetStandardDateList.value.length) {
          ElMessage({
            message: "项目分类中必须包含预算标准！",
            type: "error",
          });
          return;
        }
        //校验预算信息各项是否全部填写
        let notNullFlag = true;
        outer: for (let i = 0; i < budgetStandardDateList.value.length; i++) {
          for (let key in budgetStandardDateList.value[i]) {
            if (budgetStandardDateList.value[i][key] == "") {
              notNullFlag = false;
              break outer;
            }
          }
        }
        if (!notNullFlag) {
          ElMessage({
            message: "请检查预算信息各项是否填写！",
            type: "error",
          });
          return;
        }
        //校验单个预算标准中的起始时间是否小于结束时间
        let timeFlag = true;
        for (let i = 0; i < budgetStandardDateList.value.length; i++) {
          const currentStartTimes = new Date(budgetStandardDateList.value[i].startDate).getTime();
          const currentEndTimes = new Date(budgetStandardDateList.value[i].endDate).getTime();
          if (currentStartTimes > currentEndTimes) {
            timeFlag = false;
            break;
          }
        }
        if (!timeFlag) {
          ElMessage({
            message: "开始时间不能大于结束时间！",
            type: "error",
          });
          return;
        }
        //校验是否存在相同的预算标准
        const ids = new Set(budgetStandardDateList.value.map((item) => item.budgetStandardId));
        if (ids.size < budgetStandardDateList.value.length) {
          ElMessage({
            message: "预算标准不能重复！",
            type: "error",
          });
          return;
        }
        //校验各个预算标准起始年度和结束年度是否有交叉
        let yearFlag = true;
        outerLoop: for (let i = 0; i < budgetStandardDateList.value.length; i++) {
          let currentElement = budgetStandardDateList.value[i];
          const currentStartTimes = new Date(currentElement.startDate).getTime();
          const currentEndTimes = new Date(currentElement.endDate).getTime();
          let restOfArray = budgetStandardDateList.value.slice(i + 1); // 获取当前元素之后的所有元素
          for (let j = 0; j < restOfArray.length; j++) {
            const nextStartTimes = new Date(restOfArray[j].startDate).getTime();
            const nextEndTimes = new Date(restOfArray[j].endDate).getTime();
            if (
              (currentStartTimes >= nextStartTimes && currentStartTimes <= nextEndTimes) ||
              (currentEndTimes >= nextStartTimes && currentEndTimes <= nextEndTimes)
            ) {
              yearFlag = false;
              break outerLoop;
            }
          }
        }
        if (!yearFlag) {
          ElMessage({
            message: "各预算标准使用年度存在交叉！",
            type: "error",
          });
          return;
        }
        /**预算信息校验结束 */
        let res;
        let params = {
          projectType: {
            classId: projectClass,
            ...editForm,
          },
          budgetStandardDateList: budgetStandardDateList.value,
        };
        if (operateId.value) {
          params.projectType.id = operateId.value;
          res = await editRecords(params);
        } else {
          res = await addRecords(params);
        }
        if (res.code === 200) {
          ElMessage({
            message: "操作成功！",
            type: "success",
          });
          dialogVisible.value = false;
          emit("save-success");
        }
      }
    });
  } catch (error) {
    console.log(error);
  }
};
//打开弹窗
const handleOpen = () => {
  //如果不是横向项目 调取育部统计归属数据
  if (!isHxProject.value) {
    //获取教育部统计归属
    getSubjectTypes();
  }
  //获取预算标准下拉数据
  getStandardList();
};
//关闭弹窗
const handleClose = () => {
  //重置基本信息表单数据和预算信息数据
  editFormRef.value.resetFields();
  budgetStandardDateList.value = [];
  parentCategoryName.value = "";
  //未再from表单里面使用prop定义的数据需手动重置
  editForm.upCode = "";
  editForm.typeLevel = 1;
  editForm.parentId = "";
};
</script>

<style scoped lang="scss">
@import url("@/views/project/index.scss");
</style>
